//
//  FMLocationTool.m
//  flutter_device_info_plugin
//
//  Created by 小琦 on 2025/3/2.
//

#import "FMLocationTool.h"
#import "FMToolUtils.h"
#import <CoreLocation/CoreLocation.h>

@interface FMLocationTool()<CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationM;
@property (nonatomic,strong) CLLocation *location;
@property (nonatomic,strong) CLPlacemark *placemark;
@end

@implementation FMLocationTool

+ (instancetype)shareInstance {
    static FMLocationTool *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    return manager;
}

- (void)startLocation {
    [self.locationM stopUpdatingLocation];
    [self.locationM startUpdatingLocation];
}

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    [manager stopUpdatingLocation];
    
    if (locations.count == 0) return;
    
    CLLocation *location = locations.lastObject;
    
    self.location = location;
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    
    [geocoder reverseGeocodeLocation:locations.lastObject completionHandler:^(NSArray *array, NSError *error) {
        if (error) {
            return;
        }
        
        if (array.count) {
            CLPlacemark *placemark = array.firstObject;
            self.placemark = placemark;
            
            
            if (self.contactHandle) {
                self.contactHandle([self locationInfo]);
            }
        }
    }];
}

- (NSDictionary *)locationInfo {
    NSString *c = self.placemark.country;
    NSString *ad = self.placemark.administrativeArea;
    NSString *lo = self.placemark.locality;
    NSString *sub = self.placemark.subLocality;
    NSString *str = self.placemark.thoroughfare;
    NSString *code = self.placemark.ISOcountryCode;
    CLLocationDegrees latitude = self.location.coordinate.latitude;
    CLLocationDegrees longitude = self.location.coordinate.longitude;
    
    return @{
        @"denying":FMUtils.safeString(ad),
        @"night":FMUtils.safeString(code),
        @"working":FMUtils.safeString(c),
        @"educate":FMUtils.safeString(str),
        @"support":latitude == 0 ? @"0" : [NSString stringWithFormat:@"%.6f",latitude],
        @"prudence":longitude == 0 ? @"0" : [NSString stringWithFormat:@"%.6f",longitude],
        @"tact":FMUtils.safeString(lo),
        @"combined":FMUtils.safeString(sub),
    };
}

#pragma mark - lazy

- (CLLocationManager *)locationM {
    if (!_locationM) {
        _locationM = [[CLLocationManager alloc] init];
        _locationM.delegate = self;
        [_locationM requestWhenInUseAuthorization];
        _locationM.desiredAccuracy = kCLLocationAccuracyBest;
        _locationM.distanceFilter = 0.01;
    }
    return _locationM;
}

@end
